import time
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js
from .base import BaseBrush


class Nanshanke(BaseBrush):
    login_url = "http://vip.bjzzjh.com/Account/Login"
    index_url = "http://vip.bjzzjh.com/member/home"
    check_url = "http://vip.bjzzjh.com/Member/SellTaskMoneyOrder/List"

    def __init__(self, config, tab):
        super().__init__("南山客", "nanshanke", config, tab)

    def login(self):
        if self.browser.current_url != self.login_url:
            self.browser.get(self.login_url)

        self.enter_text((By.ID, "username"), self.username)
        self.enter_text((By.ID, "password"), self.password)
        self.click_button((By.CSS_SELECTOR, "input.submit_btn"))

        while self.browser.current_url != self.index_url:
            time.sleep(0.1)

        self.browser.get(self.check_url)

    def check_user(self):
        table = self.find_element((By.TAG_NAME, "tbody"))
        trs = table.find_elements_by_css_selector("tr.el-table__row")
        flag = True
        for tr in trs:
            text = tr.find_element_by_css_selector("td.el-table_1_column_5").\
                find_element_by_tag_name("span").get_attribute('textContent').strip()
            if text != "待审核":
                continue
            flag = False
            self.print_log("发现待验买号.")
            username = tr.find_element_by_css_selector("td.el-table_1_column_6").\
                find_element_by_css_selector('p[title="试客买号"]').get_attribute('textContent').strip()
            self.print_log(f"当前待验买号为：【{username}】")
            start = time.time()
            result = self.check.check_user(username, self.print_log)
            self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

            buttons = tr.find_element_by_css_selector("td.el-table_1_column_7").find_elements_by_tag_name("button")
            start_button, rematch_button = buttons[0], buttons[1]
            if result:
                click_by_js(self.browser, start_button)
                ok_button = self.find_element((By.CSS_SELECTOR, "div.el-message-box__btns")).find_elements_by_tag_name("button")[1]
                click_by_js(self.browser, ok_button)
                self.print_log("开始任务.\n")
            else:
                click_by_js(self.browser, rematch_button)
                ok_button = self.find_element((By.CSS_SELECTOR, "div.el-message-box__btns")).find_elements_by_tag_name("button")[1]
                click_by_js(self.browser, ok_button)
                self.print_log("开始重新匹配买号.\n")
        if flag:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False
        else:
            self.sleep(2)
            return True
